/*
 * @(#)MaintContactPersonAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.contact.web;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.contact.ContactErrorConstant;
import com.dcivision.contact.bean.ContactList;
import com.dcivision.contact.bean.MtmContactListObjectLink;
import com.dcivision.contact.dao.ContactListDAObject;
import com.dcivision.contact.dao.MtmContactListObjectLinkDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintContactPersonAction.java

  This class is for maint contact person.

    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   05/01/2005
    @version         $Revision: 1.11 $
*/

public class MaintContactGroupAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.11 $";

  public MaintContactGroupAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.contact.dao.ContactListDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.CONTACT_GROUP);
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintContactGroupForm maintForm = (MaintContactGroupForm)form;

    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    log.debug( ((maintForm!=null) ? maintForm.getClass().getName() : "")+", OP Mode:"+opMode+", Nav Mode:"+navMode);

    // Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    try {
      if (GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode)) {
        // Insert and New operation.
        try {
          this.insertRecord(mapping, maintForm, request, response);
          this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
          this.commit(request);
          form.reset(mapping, request);
          this.init(mapping, maintForm, request, response);
          maintForm.setUserIDs(null);
          maintForm.setUserGroups(null);
          maintForm.setUserRoles(null);
          maintForm.setContactPersonIDs(null);
          addMessage(request, MESSAGE_RECORD_INSERT);
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        } else {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        }
      }else if(GlobalConstant.OP_MODE_REFRESH.equals(opMode)){
        this.refreshFormData(mapping, maintForm, request, response);
        return mapping.findForward(navMode);
      }else{
        return super.execute(mapping,form,request,response);
      }
    }catch (ApplicationException ex) {
      handleApplicationException(request, ex);
      return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    }
  }
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MaintContactGroupForm maintForm=(MaintContactGroupForm)form;
    ContactListDAObject contactListDAO=new ContactListDAObject(sessionContainer,conn);
    MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
    
    //add record to contact list.
    ContactList contactList=new ContactList();
    if(checkDuplicatedContactGroup(request,maintForm)){
      throw new ApplicationException(ContactErrorConstant.DUPLICATE_CONTACT_GROUP);
    }else{
      contactList =(ContactList)contactListDAO.insertObject(maintForm.getFormData());
    }
    
    MtmContactListObjectLink mtmContactListObjectLink=new MtmContactListObjectLink();
    mtmContactListObjectLink.setContactListID(contactList.getID());
    if(!Utility.isEmpty(maintForm.getUserIDs())){
      //add user record.
      for(int i=0;i<maintForm.getUserIDs().length;i++){
        Integer userRecordID=TextUtility.parseIntegerObj(maintForm.getUserIDs()[i]);
        mtmContactListObjectLink.setObjectID(userRecordID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    if(!Utility.isEmpty(maintForm.getUserGroups())){
      //add user groups.
      for(int i=0;i<maintForm.getUserGroups().length;i++){
        Integer userGroupID=TextUtility.parseIntegerObj(maintForm.getUserGroups()[i]); 
        mtmContactListObjectLink.setObjectID(userGroupID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_USER_GROUP);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    if(!Utility.isEmpty(maintForm.getUserRoles())){
      //add user roles.
      for(int i=0;i<maintForm.getUserRoles().length;i++){
        Integer userRoleID=TextUtility.parseIntegerObj(maintForm.getUserRoles()[i]); 
        mtmContactListObjectLink.setObjectID(userRoleID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_USER_ROLE);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    if(!Utility.isEmpty(maintForm.getContactPersonIDs())){
      //add external contacts.
      for(int i=0;i<maintForm.getContactPersonIDs().length;i++){
        Integer contactPersonID=TextUtility.parseIntegerObj(maintForm.getContactPersonIDs()[i]); 
        mtmContactListObjectLink.setObjectID(contactPersonID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_CONTACT_PERSON);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    maintForm.setID(contactList.getID().toString());
    
  }
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    super.selectRecord(mapping,form,request,response);
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MaintContactGroupForm maintForm=(MaintContactGroupForm)form;
    MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
    
    Integer contactListID=TextUtility.parseIntegerObj(maintForm.getID());
        
    //get users
    String[] userIDs=this.getConatcts(request,MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD,contactListID);
    maintForm.setUserIDs(userIDs);
    
    //get groups
    String[] userGroups=this.getConatcts(request,MtmContactListObjectLink.OBJECT_TYPE_USER_GROUP,contactListID);
    maintForm.setUserGroups(userGroups);
    
    //get users
    String[] userRoles=this.getConatcts(request,MtmContactListObjectLink.OBJECT_TYPE_USER_ROLE,contactListID);
    maintForm.setUserRoles(userRoles);
    
    //get external contacts
    String[] contactPersonIDs=this.getConatcts(request,MtmContactListObjectLink.OBJECT_TYPE_CONTACT_PERSON,contactListID);
    maintForm.setContactPersonIDs(contactPersonIDs);
  }

  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MaintContactGroupForm maintForm=(MaintContactGroupForm)form;
    ContactListDAObject contactListDAO=new ContactListDAObject(sessionContainer,conn);
    MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
    mtmContactListObjectLinkDAO.deleteByContactListID(TextUtility.parseIntegerObj(maintForm.getID()));
    
    //update contact List
    if(checkDuplicatedContactGroup(request,maintForm)){
      throw new ApplicationException(ContactErrorConstant.DUPLICATE_CONTACT_GROUP);    
    }else{
      ContactList contactList=(ContactList)contactListDAO.updateObject(maintForm.getFormData());
    }
    
    MtmContactListObjectLink mtmContactListObjectLink=new MtmContactListObjectLink();
    mtmContactListObjectLink.setContactListID(TextUtility.parseIntegerObj(maintForm.getID()));
    if(!Utility.isEmpty(maintForm.getUserIDs())){
      //add user record.
      for(int i=0;i<maintForm.getUserIDs().length;i++){
        Integer userRecordID=TextUtility.parseIntegerObj(maintForm.getUserIDs()[i]);
        mtmContactListObjectLink.setObjectID(userRecordID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    if(!Utility.isEmpty(maintForm.getUserGroups())){
      //add user groups.
      for(int i=0;i<maintForm.getUserGroups().length;i++){
        Integer userGroupID=TextUtility.parseIntegerObj(maintForm.getUserGroups()[i]); 
        mtmContactListObjectLink.setObjectID(userGroupID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_USER_GROUP);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    if(!Utility.isEmpty(maintForm.getUserRoles())){
      //add user roles.
      for(int i=0;i<maintForm.getUserRoles().length;i++){
        Integer userRoleID=TextUtility.parseIntegerObj(maintForm.getUserRoles()[i]); 
        mtmContactListObjectLink.setObjectID(userRoleID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_USER_ROLE);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
    if(!Utility.isEmpty(maintForm.getContactPersonIDs())){
      //add external contacts.
      for(int i=0;i<maintForm.getContactPersonIDs().length;i++){
        Integer contactPersonID=TextUtility.parseIntegerObj(maintForm.getContactPersonIDs()[i]); 
        mtmContactListObjectLink.setObjectID(contactPersonID);
        mtmContactListObjectLink.setObjectType(MtmContactListObjectLink.OBJECT_TYPE_CONTACT_PERSON);
        mtmContactListObjectLinkDAO.insertObject(mtmContactListObjectLink);
      }
    }
  }
  
  protected String[] getConatcts(HttpServletRequest request,String objectType,Integer contactListID) throws ApplicationException{
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
    
    List list=mtmContactListObjectLinkDAO.getListByObjectType(objectType,contactListID);
    String[] IDs=new String[list.size()];
    for(int i=0;i<list.size();i++){
      MtmContactListObjectLink mtmContactListObjectLink=(MtmContactListObjectLink)list.get(i);
      IDs[i]=mtmContactListObjectLink.getObjectID().toString();
    } 
    return IDs;
  }
  
  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MaintContactGroupForm maintForm=(MaintContactGroupForm)form;
    MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
    
    Integer contactListID=TextUtility.parseIntegerObj(maintForm.getID());
    
    //get external contacts
    //String[] contactPersonIDs=this.getConatcts(request,MtmContactListObjectLink.OBJECT_TYPE_CONTACT_PERSON,contactListID);
    //maintForm.setContactPersonIDs(contactPersonIDs);
  }
  
  /**
   * check duplicated contact group.
   * @param request
   * @param maintForm
   * @return boolean
   * @throws ApplicationException
   */
  protected boolean checkDuplicatedContactGroup(HttpServletRequest request,MaintContactGroupForm maintForm) throws ApplicationException{
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    ContactListDAObject contactListDAO=new ContactListDAObject(sessionContainer,conn);
    List contactList=contactListDAO.getListByContactListName(maintForm.getContactListName(),maintForm.getPublicFlag());
    if(Utility.isEmpty(maintForm.getID())){
      if(contactList.size()>0){
        return true;
      }
    }else{
      for(int i=0;i<contactList.size();i++){
        ContactList tmpContactList=(ContactList)contactList.get(i);
        if(!tmpContactList.getID().toString().equals(maintForm.getID())){
          return true;
        }
      }
    }
    return false;
  }

    
}